// ============================================================================
// 基础类型定义
// ============================================================================
import { WeiboLoginUserInfo } from '@roasmax/weibo-types'
/** 日志级别 */
export type LogLevel = 'debug' | 'info' | 'warn' | 'error'

/** 任务状态 */
export type TaskStatus = 'pending' | 'scheduled' | 'running' | 'completed' | 'failed' | 'cancelled'

/** 任务类型 */
export type TaskType = 'search' | 'user' | 'trending' | 'comments' | 'followers' | 'scheduled'

/** 数据导出格式 */
export type ExportFormat = 'json' | 'csv' | 'xlsx'

// ============================================================================
// 用户和账号相关类型
// ============================================================================
export type UserInfo = WeiboLoginUserInfo;

/** 微博登录数据 */
export interface WeiboLoginData {
  id: number
  cookies: Electron.Cookie[]
  userInfo: UserInfo
  timestamp: number
  isValid: boolean
  lastValidated?: Date
  loginMethod?: 'manual' | 'auto'
}

// ============================================================================
// 任务相关类型
// ============================================================================

/** 任务日志条目 */
export interface TaskLogEntry {
  id: string
  timestamp: Date
  level: LogLevel
  message: string
  data?: Record<string, any>
  source?: string
}

/** 任务进度信息 */
export interface TaskProgress {
  current: number
  total: number
  percentage: number
  stage: string
  estimatedTimeRemaining?: number
  speed?: number
  startTime?: Date
  lastUpdateTime?: Date
}

/** 任务参数基础接口 */
export interface BaseTaskParams {
  count?: number
  dateRange?: [Date, Date]
  includeComments?: boolean
  includeReposts?: boolean
}

/** 搜索任务参数 */
export interface SearchTaskParams extends BaseTaskParams {
  keyword: string
  searchType?: 'comprehensive' | 'realtime' | 'hot'
  // 增量爬取选项
  enableIncremental?: boolean // 是否启用增量爬取
  crawlHistory?: boolean // 是否爬取历史数据
  maxPagesPerType?: number // 每种类型（最新/历史）的最大页数
  timeWindowEnabled?: boolean // 是否使用时间窗口管理
}

/** 用户任务参数 */
export interface UserTaskParams extends BaseTaskParams {
  userId: string
  includeUserInfo?: boolean
}

/** 热门任务参数 */
export interface TrendingTaskParams extends BaseTaskParams {
  category?: 'all' | 'entertainment' | 'sports' | 'tech'
}

/** 定时任务参数 */
export interface ScheduledTaskParams extends BaseTaskParams {
  keywords: string[]
  interval: number // 执行间隔（毫秒）
  maxPages?: number // 每个关键字最大爬取页数
  enabled: boolean
  lastExecuted?: Date
  nextExecution?: Date
  cronExpression?: string // 可选的cron表达式
}

/** 任务参数联合类型 */
export type TaskParams = SearchTaskParams | UserTaskParams | TrendingTaskParams | ScheduledTaskParams

/** 任务结果 */
export interface TaskResult {
  totalCount: number
  successCount: number
  errorCount: number
  dataPath: string
  fileSize?: number
  duration?: number
  errors?: string[]
}

/** 爬取任务 */
export interface ScrapeTask {
  id: string
  type: TaskType
  params: TaskParams
  status: TaskStatus
  accountId: string
  createdAt: Date
  startedAt?: Date
  completedAt?: Date
  progress?: TaskProgress
  logs?: TaskLogEntry[]
  result?: TaskResult
  priority?: number
  retryCount?: number
  maxRetries?: number
  tags?: string[]
}

// ============================================================================
// 配置相关类型
// ============================================================================

/** 爬虫配置 */
export interface CrawlerConfig {
  maxConcurrency: number
  requestDelay: number
  retryAttempts: number
  timeout: number
  userAgent?: string
  enableJavaScript?: boolean
  enableImages?: boolean
}

/** 代理配置 */
export interface ProxyConfig {
  enabled: boolean
  rotationInterval: number
  healthCheckInterval: number
  servers?: string[]
  authentication?: {
    username: string
    password: string
  }
}

/** 存储配置 */
export interface StorageConfig {
  dataPath: string
  maxFileSize: number
  retentionDays: number
  compressionEnabled?: boolean
  backupEnabled?: boolean
  backupInterval?: number
}

/** 日志配置 */
export interface LoggingConfig {
  level: LogLevel
  maxFiles: number
  maxSize: string
  enableConsole?: boolean
  enableFile?: boolean
  logPath?: string
}

/** 应用配置 */
export interface AppConfig {
  crawler: CrawlerConfig
  proxy: ProxyConfig
  storage: StorageConfig
  logging: LoggingConfig
  ui?: {
    theme?: 'light' | 'dark' | 'auto'
    language?: 'zh-CN' | 'en-US'
    autoSave?: boolean
  }
}

// ============================================================================
// 数据相关类型
// ============================================================================

/** 微博数据 */
export interface WeiboData {
  id: string
  text: string
  user: UserInfo
  createdAt: Date
  source?: string
  repostsCount?: number
  commentsCount?: number
  likesCount?: number
  images?: string[]
  video?: {
    url: string
    thumbnail?: string
    duration?: number
  }
  location?: {
    name: string
    coordinates?: [number, number]
  }
  isRepost?: boolean
  originalWeibo?: WeiboData
  tags?: string[]
}

/** 数据统计 */
export interface DataStats {
  totalTasks: number
  completedTasks: number
  failedTasks: number
  totalData: number
  totalUsers: number
  storageUsed: number
  lastUpdateTime: Date
}

/** 搜索结果 */
export interface SearchResult<T = any> {
  items: T[]
  total: number
  page: number
  pageSize: number
  hasMore: boolean
}

// ============================================================================
// 窗口和UI相关类型
// ============================================================================

/** 窗口状态 */
export interface WindowState {
  width: number
  height: number
  x?: number
  y?: number
  isMaximized: boolean
  isMinimized: boolean
  isFullscreen?: boolean
}

/** 通知类型 */
export interface NotificationData {
  id: string
  type: 'info' | 'success' | 'warning' | 'error'
  title: string
  message: string
  duration?: number
  actions?: Array<{
    label: string
    action: () => void
  }>
}

// ============================================================================
// IPC 通信类型
// ============================================================================

/** IPC 响应包装器 */
export interface IPCResponse<T = any> {
  success: boolean
  data?: T
  error?: {
    code: string
    message: string
    details?: any
  }
}

/** IPC 事件类型映射 */
export interface IPCEvents {
  // 登录相关
  'login:start': () => Promise<IPCResponse<WeiboLoginData>>
  'login:validate': (accountId: string) => Promise<IPCResponse<boolean>>
  'login:get-accounts': () => Promise<IPCResponse<WeiboLoginData[]>>
  'login:delete-account': (accountId: string) => Promise<IPCResponse<void>>
  'login:delete-invalid-accounts': () => Promise<IPCResponse<number>>

  // 任务相关
  'task:create': (task: Omit<ScrapeTask, 'id' | 'createdAt'>) => Promise<IPCResponse<ScrapeTask>>
  'task:start': (taskId: string) => Promise<IPCResponse<void>>
  'task:stop': (taskId: string) => Promise<IPCResponse<void>>
  'task:delete': (taskId: string) => Promise<IPCResponse<void>>
  'task:get-all': () => Promise<IPCResponse<ScrapeTask[]>>
  'task:get-by-id': (taskId: string) => Promise<IPCResponse<ScrapeTask | null>>
  'task:get-logs': (taskId: string) => Promise<IPCResponse<TaskLogEntry[]>>

  // 配置相关
  'config:get': () => Promise<IPCResponse<AppConfig>>
  'config:update': (config: Partial<AppConfig>) => Promise<IPCResponse<void>>
  'config:reset': () => Promise<IPCResponse<void>>

  // 数据相关
  'data:export': (taskId: string, format: ExportFormat) => Promise<IPCResponse<string>>
  'data:get-stats': () => Promise<IPCResponse<DataStats>>
  'data:get-weibo-data': (taskId: string, page?: number, pageSize?: number) => Promise<IPCResponse<SearchResult<WeiboData>>>
  'data:search-weibo': (query: string, filters?: any) => Promise<IPCResponse<SearchResult<WeiboData>>>
  'data:delete-task-data': (taskId: string) => Promise<IPCResponse<void>>

  // 系统相关
  'system:get-info': () => Promise<IPCResponse<{
    version: string
    platform: string
    arch: string
    nodeVersion: string
  }>>
  'system:open-external': (url: string) => Promise<IPCResponse<void>>
  'system:show-item-in-folder': (path: string) => Promise<IPCResponse<void>>
}

/** IPC 事件监听器类型 */
export interface IPCEventListeners {
  'task:progress-update': (taskId: string, progress: TaskProgress) => void
  'task:log-update': (taskId: string, log: TaskLogEntry) => void
  'task:status-change': (taskId: string, status: TaskStatus) => void
  'notification:show': (notification: NotificationData) => void
  'config:changed': (config: Partial<AppConfig>) => void
}

// ============================================================================
// 错误处理类型
// ============================================================================

/** 应用错误类型 */
export type AppErrorType =
  | 'NETWORK_ERROR'
  | 'AUTH_ERROR'
  | 'VALIDATION_ERROR'
  | 'DATABASE_ERROR'
  | 'FILE_SYSTEM_ERROR'
  | 'UNKNOWN_ERROR'

/** 应用错误 */
export interface AppError {
  type: AppErrorType
  code: string
  message: string
  details?: any
  timestamp: Date
  stack?: string
}

// ============================================================================
// 导出子模块类型
// ============================================================================

export * from './api'
export * from './database'
export * from './events'
